package com.molyfun.parents.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.TextUtils;
import android.widget.RemoteViews;

import com.molyfun.parents.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by ligang on 2016/9/20 0020.
 */
public class DownloadApkService extends Service {
    private UpDateReceiver receiver;
    private static final int DOWNLOAD_APK_NOTIFICATION_ID = 0;
    private NotificationManager mNotificationManager;
    private Notification mNotification;
    private int fileSize;
    private int downLoadFileSize;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    mNotification.contentView.setProgressBar(R.id.progressBar_download, fileSize, downLoadFileSize, false);
                    mNotificationManager.notify(DOWNLOAD_APK_NOTIFICATION_ID,mNotification);
                    break;
                case 2:
                    mNotification.contentView.setProgressBar(R.id.progressBar_download, fileSize, fileSize, false);
                    mNotification.contentView.setTextViewText(R.id.tv_download_progress_state,"下载完成");
                    mNotificationManager.notify(DOWNLOAD_APK_NOTIFICATION_ID,mNotification);
                    if(apkFile.exists()){
                        openFile(apkFile);
                    }
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        receiver = new UpDateReceiver();
        IntentFilter filter=new IntentFilter();
        filter.addAction("android.intent.action.MY_UPDATE_BROADCAST");
        registerReceiver(receiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String url = intent.getStringExtra("apk_url");
            if (!TextUtils.isEmpty(url)) {
                startDownLoad(url);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void startDownLoad(final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                        String name=path.substring(path.lastIndexOf("/")+1,path.length());
                        String sdpath = Environment.getExternalStorageDirectory() + "/hello/";
                        URL url = new URL(path);
                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.connect();
                        fileSize = conn.getContentLength();
                        InputStream is = conn.getInputStream();
                        File file = new File(sdpath);
                        if (!file.exists()){
                            file.mkdir();
                        }
                        apkFile = new File(sdpath, name);
                        if (apkFile.exists()){
                            apkFile.delete();
                        }
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        notificationInit();
                        int numread ;
                        byte[] buf = new byte[1024*4];
                        while ((numread=is.read(buf))!=-1){
                            fos.write(buf, 0, numread);
                            fos.flush();
                            downLoadFileSize += numread;
                            if (downLoadFileSize%(numread*100) == 0){
                                mHandler.sendEmptyMessage(1);//更新通知栏进度
                            }
                        }
                        isDownFinish = true;
                        mHandler.sendEmptyMessage(2);//下载完成通知
                        fos.close();
                        is.close();
                    }
                } catch (MalformedURLException e){
                    e.printStackTrace();
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private void notificationInit(){
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        RemoteViews views = new RemoteViews(getPackageName(),R.layout.view_download_progress_notification_bar);
        Notification.Builder builder = new Notification.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher).setTicker("文件下载").setContent(views);
        Intent intent = new Intent("android.intent.action.MY_UPDATE_BROADCAST");
        PendingIntent pIntent = PendingIntent.getBroadcast(this,0,intent,0);
        views.setOnClickPendingIntent(R.id.ll_download_progress,pIntent);
        mNotification = builder.build();
        mNotification.contentIntent = pIntent;
        mNotificationManager.notify(DOWNLOAD_APK_NOTIFICATION_ID,mNotification);
    }

    private boolean isDownFinish = false;
    File apkFile;

    /**
     * 安转apk
     * @param file
     */
    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        startActivity(intent);
    }

    public class UpDateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.intent.action.MY_UPDATE_BROADCAST")) {
                if (isDownFinish) {
                    mNotificationManager.cancel(DOWNLOAD_APK_NOTIFICATION_ID);
                    collapseStatusBar();
                    if (apkFile.exists()) {
                        openFile(apkFile);
                    }
                }
            }
        }
    }

    /**
     * 关闭下拉通知栏
     * 需要添加权限：<uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />
     */
    private void collapseStatusBar() {
        try {
            Object statusBarManager = getSystemService("statusbar");
            Method collapse;
            if (Build.VERSION.SDK_INT <= 16) {
                collapse = statusBarManager.getClass().getMethod("collapse");
            } else {
                collapse = statusBarManager.getClass().getMethod("collapsePanels");
            }
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }
}
